﻿using Microsoft.EntityFrameworkCore;
using Project.IRepository;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.Service
{
    /// <summary>
    /// 用户工具关系
    /// </summary>
    public class UserDesignToolService: IUserDesignToolService
    {
        private readonly ProjectDbContext dbContext;
        private readonly IUnitOfWork unitOfWork;

        public UserDesignToolService(ProjectDbContext dbContext, IUnitOfWork unitOfWork)
        {
            this.dbContext = dbContext;
            this.unitOfWork = unitOfWork;
        }


        /// <summary>
        /// 根据用户id获取设计工具
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IQueryable<DesignTool> GetDesignTools(Guid userId)
        {
            return dbContext.UserDesignRelation.Where(b => b.UserId == userId).Include(n => n.DesignTool)
                 .Select(n => n.DesignTool).Where(n => n.IsDeleted == false);
        }

        /// <summary>
        /// 设置用户设计工具
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="designToolIds"></param>
        /// <returns></returns>
        public async Task<int> SetDesignToolsAsync(Guid userId, List<Guid> designToolIds)
        {
            var existsTids = await GetDesignTools(userId).Select(n => n.Id).ToListAsync(); // 现存在的工具对象id
            var deleteingTids = existsTids.Except(designToolIds); // 要删除的项
            var addingTids = designToolIds.Except(existsTids);  // 要新增的项

            // 移除
            foreach (var bid in deleteingTids)
            {
                dbContext.UserDesignRelation.Remove(new UserDesignRelation() { UserId = userId, DesignToolId = bid });
            }

            // 增加
            foreach (var bid in addingTids)
            {
                dbContext.UserDesignRelation.Add(new UserDesignRelation() { UserId = userId, DesignToolId = bid });
            }

            return await unitOfWork.SaveChangesAsync();
        }
    }
}
